package com.douwong.student.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.douwong.student.R;
import com.douwong.student.adapter.ImageAdapter;
import com.douwong.student.adapter.MemberAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.ClassBaseActivity;
import com.douwong.student.contant.Config;
import com.douwong.student.enums.E_CommandType;
import com.douwong.student.enums.E_Destination;
import com.douwong.student.factory.ThreadFactory;
import com.douwong.student.model.DiscussSendData;
import com.douwong.student.model.GroupFile;
import com.douwong.student.model.ResultAnswer;
import com.douwong.student.model.StudentInfo;
import com.douwong.student.popuwindow.ImageShowPopu;
import com.douwong.student.popuwindow.LeaderPopuwindow;
import com.douwong.student.popuwindow.RecordPopu;
import com.douwong.student.socket.LTPServer;
import com.douwong.student.utils.AudioRecorder2Mp3Util;
import com.douwong.student.utils.DateTools;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.FtpUtils;
import com.douwong.student.utils.ImageUtils;
import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.ScreenUtils;
import com.douwong.student.utils.TimeReduce;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;
import com.douwong.student.view.MyGridView;
import com.zfdang.multiple_images_selector.ImagesSelectorActivity;
import com.zfdang.multiple_images_selector.SelectorSettings;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.UUID;

import static com.douwong.student.contant.Config.FINSH_DISCUSSEND;

/**
 * @autor yichao
 * @time 2017/4/1315:34
 * @des 小组讨论
 */
public class GroupTalkActivity extends ClassBaseActivity implements View.OnClickListener {
    public static boolean isShow;
    private boolean isCommit=false;
    private boolean isEnd=false;
    private View leader_choose, leader_view;
    private TextView time, lead_text, leader_members_text, leader_title, leader_time, text;
    private RelativeLayout rand_leader,select_leader;
    private ImageView leader_pic,leader_img,commit;
    private MyGridView img_view;
    private  GridView group_member;
    private MemberAdapter mMemberAdapter;
    private Timer mTimer;
    private int  mGrabGroupTime = 30;
    private final  int count_downing=5001;//正在倒计时
    private final  int count_downed=5002;//倒计时完成
    private final  int closeleaderPopu=5003;//关闭组长弹窗
    private boolean hasSelected=false;
    private DiscussSendData mDiscussSendData;
    private String leadName = "";
    private final int FTP_DOWN_SUCCESS = 221;
    private final int FTP_DOWN_FAIL = 222;
    private Bitmap mBitmap;
    private TimeReduce mTimeReduce;
    private LinearLayout mLlTimerRoot,mLlCommitRoot;
    private LeaderPopuwindow mLeaderPopuwindow;
    private List<GroupFile> mResultList;
    private ImageAdapter mImageAdapter;
    private RecordPopu mRecordPopu;
    public final  int CAMERA_REQUEST_CODE = 2001;
    public final  int ALBUM_REQUEST_CODE = 3002;
    public final  int HAND_BOARD = 3003;
    private int record;
    private long voiceBegin = 0;
    private long voiceStop = 0;
    private AudioRecorder2Mp3Util util;
    private List<ResultAnswer> mResultAnswerList;
    private LinkedList<File> mFileLinkedList;
    private String mFileAbsolutePath;
    private String mUuidStr;
    private  final int REQUEST_CODE = 732;//启动画廊
    private ArrayList<String> mStringList;

    @Override
    protected void initView() {

        setContentView(R.layout.group_talk);
        leader_choose = findViewById(R.id.leader_choose);
        leader_view = findViewById(R.id.leader_view);
        rand_leader = (RelativeLayout) findViewById(R.id.rand_leader);
        select_leader = (RelativeLayout) findViewById(R.id.select_leader);
        time = (TextView) findViewById(R.id.time);
        text = (TextView) findViewById(R.id.text);
        lead_text = (TextView) findViewById(R.id.lead_text);
        leader_members_text = (TextView) findViewById(R.id.leader_members_text);
        leader_title = (TextView) findViewById(R.id.leader_title);// 题目
        leader_time = (TextView) findViewById(R.id.leader_time);
        leader_pic = (ImageView) findViewById(R.id.leader_pic);
        group_member = (GridView) findViewById(R.id.group_member);
        img_view = (MyGridView) findViewById(R.id.img_view);
        leader_img = (ImageView) findViewById(R.id.leader_img);// 题目图片
        commit = (ImageView) findViewById(R.id.commit); //提交
        mLlTimerRoot = (LinearLayout) findViewById(R.id.time_ll);
        mLlCommitRoot = (LinearLayout) findViewById(R.id.commit_ll);
    }
    @Override
    protected void initData() {
        super.initData();
        mStringList = new ArrayList<>();
        mUuidStr = UUID.randomUUID().toString();
        isShow=false;
        mTimer = new Timer();
        mLlCommitRoot.setVisibility(View.GONE);
        text.setText("正在选择组长...");
        mResultList = new ArrayList<GroupFile>();
        GroupFile discussResult = new GroupFile();
        discussResult.fileName = "add";
        mResultList.add(discussResult);
        mImageAdapter = new ImageAdapter(this,mResultList);
        img_view.setAdapter(mImageAdapter);

        registerReceiver(mReceiver,mFilter);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        rand_leader.setOnClickListener(this);
        select_leader.setOnClickListener(this);
        commit.setOnClickListener(this);
        leader_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageShowPopu popu = new ImageShowPopu(GroupTalkActivity.this, mFileAbsolutePath,
                        ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight());
                popu.showAtLocation(v, Gravity.CENTER, 0, 0);
            }
        });

        group_member.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //选择组长
                if (hasSelected) {
                    Toast.makeText(GroupTalkActivity.this, "你已选定，不能再选", Toast.LENGTH_LONG).show();
                } else {
                    leadName = "你推荐" + mDiscussSendData.getMember().get(position).studentRemark + "当组长";
                    sendLeaderInfor(mDiscussSendData.getMember().get(position).getStudentId());
                }
            }
        });
        img_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (mResultList.get(arg2).fileName.equals("add")) {
                    AnswerTypeShow();

                } else {
                    if (mResultList.get(arg2).fileType == 1) {// 图片
                        ImageShowPopu popu = new ImageShowPopu(GroupTalkActivity.this, mResultList.get(arg2).filePath,
                                ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight());
                        popu.showAtLocation(arg1, Gravity.CENTER, 0, 0);
                    } else if (mResultList.get(arg2).fileType == 2) {// 语音
                        mRecordPopu = new RecordPopu(GroupTalkActivity.this,
                                mResultList.get(arg2).filePath, mResultList.get(arg2).time);
                        mRecordPopu.showAtLocation(arg1, Gravity.CENTER, 0, 0);
                        mRecordPopu.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override

                            public void onDismiss() {
                                mRecordPopu.player.release();
                                mRecordPopu.player = null;
                            }
                        });
                    }
                }
            }
        });
    }



    // 答案类型
    private void AnswerTypeShow() {
        AlertDialog.Builder builder = new AlertDialog.Builder(GroupTalkActivity.this);
        String[] str = new String[] { "拍照", "相册", "语音", "手写板" };
        builder.setItems(str, new DialogInterface.OnClickListener() {

            @SuppressLint("SdCardPath")
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        cameraUpload();
                        break;
                    case 1:
                     /*   Intent intent2 = new Intent(Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent2, ALBUM_REQUEST_CODE);*/

                        // start multiple photos selector
                        Intent intent2 = new Intent(GroupTalkActivity.this, ImagesSelectorActivity.class);
                        // max number of images to be selected

                        intent2.putExtra(SelectorSettings.SELECTOR_MAX_IMAGE_NUMBER,  5- mResultList.size());
                        // min size of image which will be shown; to filter tiny images (mainly icons)
                        intent2.putExtra(SelectorSettings.SELECTOR_MIN_IMAGE_SIZE, 100000);
                        // show camera or not
                        intent2.putExtra(SelectorSettings.SELECTOR_SHOW_CAMERA, false);
                        // pass current selected images as the initial value
                        intent2.putStringArrayListExtra(SelectorSettings.SELECTOR_INITIAL_SELECTED_LIST, mStringList);
                        // start the selector
                        startActivityForResult(intent2, REQUEST_CODE);

                        break;
                    case 2:
                        record++;
                        mRecordPopu = new RecordPopu(GroupTalkActivity.this, GroupTalkActivity.this);
                        voiceBegin = System.currentTimeMillis();
                        mRecordPopu.showAtLocation(img_view, Gravity.CENTER, 0, 0);
                        mRecordPopu.setOnDismissListener(new PopupWindow.OnDismissListener() {

                            @Override
                            public void onDismiss() {
                                if (util != null) {
                                    mRecordPopu.setRecord(false);
                                    util.cleanFile(AudioRecorder2Mp3Util.RAW);
                                    util.close();
                                    util = null;
                                }
                            }
                        });
                        if (util == null) {
                            util = new AudioRecorder2Mp3Util(GroupTalkActivity.this,
                                    // "/sdcard/test_audio_recorder_for_mp3.raw",
                                    // "/sdcard/test_audio_recorder_for_mp3.mp3");
                                    FileUtils.VOICE_DIR + BaseApplication.sUserBean.getUserbean().getId()+mUuidStr + "audio_recorder_for_mp3_"
                                            + record + ".raw",
                                    FileUtils.VOICE_DIR + BaseApplication.sUserBean.getUserbean().getId() +mUuidStr+ "audio_recorder_for_mp3_"
                                            + record + ".mp3");
                        }
                        util.startRecording();
                        break;
                    case 3:
                        Intent intent = new Intent(GroupTalkActivity.this,HandWriteBoardActivity.class);
                        intent.putExtra("content", "第" + mDiscussSendData.getGroupId() + "组");
                        startActivityForResult(intent, HAND_BOARD);
                        break;
                }
            }
        });
        builder.show();
    }

    protected void cameraUpload() {
        Intent intentCP=new Intent(this, CaptureActivity.class);
        intentCP.putExtra("router", 0);
        startActivityForResult(intentCP,CAMERA_REQUEST_CODE);

    }

    /**
     * 发送选定的组长信息
     * @param member  推荐组长id
     */
    private void sendLeaderInfor(int member) {
        if (BaseApplication.isLoginClass){
            hasSelected=true;
            lead_text.setText(leadName);
             LTPServer.createInstance(this).sendMsg(member, E_CommandType.discussVote, E_Destination.teacher,new int[]{BaseApplication.sTeacherOnline.teacher.teacherId});
            leader_choose.setVisibility(View.INVISIBLE);
            leader_view.setVisibility(View.VISIBLE);
            if (mTimer!=null){
                mTimer.cancel();
            }
        }
    }

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
         /*       case count_downing:
                    mGrabGroupTime--;
                    if (mGrabGroupTime >= 0) {
                        time.setText(mGrabGroupTime + "");
                    } else {
                        time.setVisibility(View.GONE);
                    }

                    break;
                case count_downed:
                    if (!hasSelected){
                    //随机抢组长
                        int grouderId = getRandomNumber();
                        sendLeaderInfor(grouderId);
                    }
                    break;*/
                case closeleaderPopu:
                    if (mLeaderPopuwindow!=null && mLeaderPopuwindow.isShowing()){
                        try {
                            mLeaderPopuwindow.dismiss();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    break;
            }

        }
    };

    IntentFilter mFilter=new IntentFilter(){
        {addAction(Config.GROUP_DISCUSSION_SEND);
         addAction(Config.TEACHER_LEAVE_CLASS);
            addAction(Config.GROUP_DISCUSSION_FILE_DOWN_SUCCESS);
            addAction(Config.GROUP_DISCUSSION_FILE_DOWN_FAILURE);
            addAction(Config.GROUP_DISCUSSION_CONFIRM_LEADER);
            addAction(Config.LOGIN_CLASS_FAILURE);
            addAction(FINSH_DISCUSSEND);




        }
    };
    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Config.GROUP_DISCUSSION_SEND:
                    String stringExtra = intent.getStringExtra(Config.INTENT_DATA);
                    mDiscussSendData = JsonUtils.parseString(stringExtra, DiscussSendData.class);
                    if (mDiscussSendData !=null){


                      //倒计时抢组长
                      /*  mTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                if (mGrabGroupTime == 0) {
                                    mHandler.sendEmptyMessage(count_downed);
                                } else {
                                    mHandler.sendEmptyMessage(count_downing);
                                }
                            }
                        },100,1000);*/

                    //下载图片
                  //   downFilePic(mDiscussSendData.getAnnex());
                    //考试倒计时
                    if (mDiscussSendData.limitDate!=0){
                        mLlTimerRoot.setVisibility(View.VISIBLE);
                        mTimeReduce = new TimeReduce(leader_time, mDiscussSendData.limitDate*60, GroupTalkActivity.this);
                        mTimeReduce.setTimerOverListener(new TimeReduce.TimerOver() {
                            @Override
                            public void timerOver() {
                                //倒计时到了
                                mLlTimerRoot.setVisibility(View.GONE);
                                //提交答案
                                isEnd=true;
                                mImageAdapter.setEnd(true);
                                commitResult();


                            }
                        });

                    }
                    //题目
                    leader_title.setText( mDiscussSendData.getSubject());
                    String memberInfos="";
                    List<DiscussSendData.Member> members = mDiscussSendData.getMember();
                    for (int i = 0; i <members.size(); i++) {
                        memberInfos= memberInfos+ members.get(i).getStudentRemark()+",";
                    }
                    leader_members_text.setText(memberInfos);
                    //显示成员
                    mMemberAdapter = new MemberAdapter(GroupTalkActivity.this, mDiscussSendData.getMember());
                    group_member.setAdapter(mMemberAdapter);
                    }
                    break;

                case Config.GROUP_DISCUSSION_FILE_DOWN_SUCCESS:
                    ToastUtils.makeText(GroupTalkActivity.this,"附件下载成功");
                    mFileAbsolutePath = intent.getStringExtra(Config.INTENT_DATA);
                    BitmapFactory.Options opts=new BitmapFactory.Options();
                    opts.inJustDecodeBounds=true;
                    BitmapFactory.decodeFile(mFileAbsolutePath,opts);
                    opts.inPreferredConfig = Bitmap.Config.ARGB_4444;
                    opts.inSampleSize = calculateInSampleSize(opts, ScreenUtils.getScreenWidth(), 250);
                    opts.inJustDecodeBounds=false;
                    mBitmap =  BitmapFactory.decodeFile(mFileAbsolutePath,opts);
                    leader_img.setVisibility(View.VISIBLE);
                    leader_img.setImageBitmap(mBitmap);
                    break;
                case Config.GROUP_DISCUSSION_FILE_DOWN_FAILURE:
                    ToastUtils.makeText(GroupTalkActivity.this,"附件下载失败");
                    break;
                case Config.GROUP_DISCUSSION_CONFIRM_LEADER:
                    //选取组长
                    leader_choose.setVisibility(View.GONE);
                    leader_view.setVisibility(View.VISIBLE);
                    String leaderInfos = intent.getStringExtra(Config.INTENT_DATA);
                    StudentInfo leaderInfo = JsonUtils.deserialize(leaderInfos, StudentInfo.class);
                    if (leaderInfo!=null){
                        mLeaderPopuwindow = new LeaderPopuwindow(GroupTalkActivity.this,leaderInfo.getStudentRemark()+"晋升为组长");
                        mLeaderPopuwindow.showAtLocation(lead_text, Gravity.CENTER, 0, 0);
                        lead_text.setText("选取"+leaderInfo.studentRemark+"为组长");
                        mHandler.sendEmptyMessageDelayed(closeleaderPopu, 3000);
                    }
                    if (leaderInfo.studentId==BaseApplication.sUserBean.getUserbean().getId()){
                        //自己是组长
                        text.setText("请添加讨论答案,提交讨论结果！");
                        mLlCommitRoot.setVisibility(View.VISIBLE);
                    }else {
                        text.setText("等待组长提交讨论结果！");
                    }
                    break;
                case Config.TEACHER_LEAVE_CLASS:
                case Config.LOGIN_CLASS_FAILURE:
                case  Config.FINSH_DISCUSSEND:
                    finish();
                    break;
            }

        }
    };
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA_REQUEST_CODE) {

                saveFile(data.getStringExtra("picPath"));
            } else if (requestCode == ALBUM_REQUEST_CODE) {

                Uri selectedImage = data.getData();
                String[] filePathColumns = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                int i = 0;
                if (c.moveToNext()) {
                    int columnIndex = c.getColumnIndex(filePathColumns[i]);
                    String filePath = c.getString(columnIndex);
                    saveFile(filePath);
                }
            } else if (requestCode == HAND_BOARD) {
                addImage(data.getStringExtra("filePath"), 0);
            }else  if (requestCode ==REQUEST_CODE){
                //多选画廊
                ArrayList<String> filesList=         data.getStringArrayListExtra(SelectorSettings.SELECTOR_RESULTS);

                if (filesList!=null &&filesList.size()>0){

                    for (String filePath:filesList) {
                        logcatI("画廊 的图片 路径 ："+filePath);
                        saveFile(filePath);

                    }
                }

            }

        }
    }
    private void saveFile(String filePath) {
        File tempFile = new File(filePath);
        String imgName = FileUtils.IMAGE_DIR + BaseApplication.sUserBean.getUserbean().getId() + UIUtils.getUUidString()+ DateTools.getStringTime()
                + ".jpg";
        File file = new File(imgName);
        if (!file.exists()) {
            try {
                file.createNewFile();
                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 4;
                Bitmap dstBitmap = null;
                if (tempFile.length() > 200 * 1024) {
                    dstBitmap = BitmapFactory.decodeFile(filePath, options);
                    bitmap = ImageUtils.imageZoomLimtSize(dstBitmap, 200);
                    bitmap=FileUtils.createNewBitmap(bitmap,"第" + mDiscussSendData.getGroupId() + "组",GroupTalkActivity.this, Color.WHITE);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
                } else {
                    dstBitmap = BitmapFactory.decodeFile(filePath);
                    dstBitmap=FileUtils.createNewBitmap(dstBitmap,"第" + mDiscussSendData.getGroupId() + "组",GroupTalkActivity.this,Color.WHITE);
                    dstBitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        addImage(imgName, 0);
    }



    /**
     * 获取随机组长
     * return 组长id
     */
    private int getRandomNumber() {
        Random random = new Random();
        List<DiscussSendData.Member> member = mDiscussSendData.getMember();
        if(member.size()>1){
            int number = random.nextInt(member.size() - 1);
           leadName = "随机推荐" + member.get(number).getStudentRemark() + "当组长";
           // sendLeaderInfor(memberInfors.get(number));
          return   member.get(number).getStudentId();
        }
        return -1;
    }

    public static  void startActivity(Context context){
        Intent intent=new Intent(context,GroupTalkActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        isShow=false;
        hasSelected=false;
        if (mReceiver!=null){
            unregisterReceiver(mReceiver);
        }
        if (mBitmap!=null &&!mBitmap.isRecycled()){
            mBitmap.recycle();
            mBitmap=null;
            System.gc();
        }
        if (mRecordPopu!=null &&mRecordPopu.isShowing()){
            mRecordPopu.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.confir_text:
                util.stopRecordingAndConvertFile();
                util.close();
                voiceStop = System.currentTimeMillis();
                addImage(FileUtils.VOICE_DIR + BaseApplication.sUserBean.getUserbean().getId() +mUuidStr+ "audio_recorder_for_mp3_" + record
                        + ".mp3", 2);
                util.cleanFile(AudioRecorder2Mp3Util.RAW);
                util = null;
                mRecordPopu.dismiss();
                break;
            case R.id.cancel_text:
                util.cleanFile(AudioRecorder2Mp3Util.RAW);
                util.close();
                util = null;
                mRecordPopu.dismiss();
                break;

            case R.id.select_leader :
                //抢组长
                if (hasSelected){
                    Toast.makeText(GroupTalkActivity.this, "你已选定，不能再选", Toast.LENGTH_LONG).show();
                    return;
                }
                leadName = "你推荐自己当组长";
                sendLeaderInfor(BaseApplication.sStudentOnline.get_student().studentId);
                break;
            case R.id.rand_leader :
                //随机组长
             if (hasSelected){
                     Toast.makeText(GroupTalkActivity.this, "你已选定，不能再选", Toast.LENGTH_LONG).show();
                 return;
             }
                int randomNumber = getRandomNumber();
                if (randomNumber!=-1){
                    sendLeaderInfor(randomNumber);
                }
                break;

        case R.id.commit:
            //提交
            commitResult();
            break;


        }
    }

    /**
     * 提交答案
     */
    private void commitResult() {
     if (!isCommit ){
         //没提交
         if (mResultList.size()>1){
             //有答案
             if (BaseApplication.isLoginClass){
                 //上传答案
                 ///classroom/(学校ID)/student/(学生ID)/discuss	小组讨论文件
            final      String fileDir="/classroom/"+BaseApplication.sUserBean.getSchoolId()+"/student/"
                        +BaseApplication.sUserBean.getPersonalbean().getId()
                         +"/discuss/";
               //  /classroom/(学校ID)/student/(学生ID)/upload
                 ResultAnswer resultAnswer;
                 mResultAnswerList = new ArrayList<>();
                 mFileLinkedList = new LinkedList<>();

                 for (int i = 0; i < mResultList.size(); i++) {


                             GroupFile groupFile = mResultList.get(i);
                             if (groupFile.fileType==1){
                                 resultAnswer = new ResultAnswer(true,1,fileDir+groupFile.fileName,groupFile.size);
                                 logcatI(resultAnswer.toString());
                                 mFileLinkedList.add(groupFile.mFile);
                                 mResultAnswerList.add(resultAnswer);
                             }else if (groupFile.fileType==2){
                                 resultAnswer = new ResultAnswer(true,2,fileDir+groupFile.fileName,groupFile.size);
                                 logcatI(resultAnswer.toString());
                                 mFileLinkedList.add(groupFile.mFile);
                                 mResultAnswerList.add(resultAnswer);
                             }

                             //    /classroom/(学校ID)/teacher/(老师ID)/(班级ID)/discuss	老师所在的班级小组讨论文件
                             //ftp上传
                      /*   FtpUtils ftpUtils=new FtpUtils();
                         ftpUtils.uploadMultiFile();*/
                 }
                 ThreadFactory.getDownLoadPool().execute(new Runnable() {
                     @Override
                     public void run() {
                         //
                         FtpUtils ftpUtils=new FtpUtils();
                         try {
                             ftpUtils.uploadMultiFile(mFileLinkedList, fileDir, new FtpUtils.UploadProgressListener() {
                                 @Override
                                 public void onUploadProgress(String currentStep, long uploadSize, File file) {
                                     if (Config.FTP_DISCONNECT_SUCCESS.equals(currentStep)){
                                         //上传完成
                                         ToastUtils.makeText(GroupTalkActivity.this,"上传文件完成");
                                         LTPServer.createInstance(GroupTalkActivity.this).sendMsg(mResultAnswerList,E_CommandType.discussSubmit,E_Destination.teacher,new int[]{BaseApplication.sTeacherOnline.teacher.teacherId});
                                     }else if (Config.FTP_CONNECT_FAIL.equals(currentStep)){

                                         ToastUtils.makeText(GroupTalkActivity.this,currentStep);
                                     }
                                 }
                             });
                         } catch (Exception e) {
                             e.printStackTrace();
                             ToastUtils.makeText(GroupTalkActivity.this,"上传文件错误");
                         }

                     }
                 });

                 isCommit=true;
                 mImageAdapter.setCommit(true);
                 commit.setSelected(true);
                 if (mResultList.size() > 0&& mResultList.get(mResultList.size() - 1).fileName.equals("add")) {
                     mResultList.remove(mResultList.size() - 1);
                     mImageAdapter.notifyDataSetChanged();
                 }

             }else {
                 ToastUtils.makeText(this,"请先加入课堂");
             }

         }else {
             ToastUtils.makeText(this,"请先讨论");
             if (isEnd){
                 Toast.makeText(GroupTalkActivity.this, "讨论已经,不能提交！", Toast.LENGTH_LONG).show();
                 //已经提交
                 commit.setSelected(true);
                 commit.setFocusable(false);
                 if (mResultList.size()>0 &&  mResultList.get(mResultList.size() - 1).fileName.equals("add")  ){
                     mResultList.remove(mResultList.size() - 1);
                     mImageAdapter.notifyDataSetChanged();
                 }
             }
         }

     }else {
         if (isEnd) {
             Toast.makeText(GroupTalkActivity.this, "讨论已经,不能提交！", Toast.LENGTH_LONG).show();
         } else {
             Toast.makeText(GroupTalkActivity.this, "已经提交过,不能重复提交！", Toast.LENGTH_LONG).show();
         }
         //已经提交
         commit.setSelected(true);
         commit.setFocusable(false);
         if (mResultList.size()>0 &&  mResultList.get(mResultList.size() - 1).fileName.equals("add")  ){
             mResultList.remove(mResultList.size() - 1);
             mImageAdapter.notifyDataSetChanged();

         }

     }

    }

    /**
     *添加图片显示在grivdView
     * @param filePath
     * @param type
     */

    private void addImage(String filePath, int type) {
        if (isCommit) {
            return;
        }
        GroupFile result = new GroupFile();
        File file = new File(filePath);
        result.fileName = file.getName();
        if (type == 0) {
            result.fileType = 1;//图片
        } else {
            result.fileType = 2;//音频
        }
        mResultList.remove(mResultList.size() - 1);
        result.filePath = filePath;
        if (type == 2) {
            int voiceTime = (int) (voiceStop - voiceBegin) / 1000;
            result.time = voiceTime;
        }
        result.mFile=file;
        result.size=file.length();

        mResultList.add(result);
        if (mResultList.size() < 4) {
            GroupFile discussResult = new GroupFile();
            discussResult.fileName = "add";
            mResultList.add(discussResult);
        }

        mImageAdapter.notifyDataSetChanged();
      //  commitResult(file);
    }
    /**
     * 计算缩放比例
     * @param op
     * @param reqWidth
     * @param reqheight
     * @return
     */
    public int calculateInSampleSize(BitmapFactory.Options op, int reqWidth,
                                     int reqheight) {
        int originalWidth = op.outWidth;
        int originalHeight = op.outHeight;
        int inSampleSize = 1;
        if (originalWidth > reqWidth || originalHeight > reqheight) {
            int halfWidth = originalWidth / 2;
            int halfHeight = originalHeight / 2;
            while ((halfWidth / inSampleSize > reqWidth)
                    &&(halfHeight / inSampleSize > reqheight)) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
}
